<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Java面试,">










<meta name="description" content="本文学习《剑指Java面试-Offer直通车》第七章，主要内容为: Java底层知识：GC相关视频课程地址：https://coding.imooc.com/class/303.html项目代码地址：https://gitee.com/aiolos123/java_basic本文部分内容和图片引用自博客：《Java-面试–Java8-JVM内存模型》 https://www.jianshu.com">
<meta name="keywords" content="Java面试">
<meta property="og:type" content="article">
<meta property="og:title" content="【二】剑指Java面试Offer直通车-Java底层知识：GC相关">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/12/18/java-interview-offer-2/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文学习《剑指Java面试-Offer直通车》第七章，主要内容为: Java底层知识：GC相关视频课程地址：https://coding.imooc.com/class/303.html项目代码地址：https://gitee.com/aiolos123/java_basic本文部分内容和图片引用自博客：《Java-面试–Java8-JVM内存模型》 https://www.jianshu.com">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219091341476.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219092028388.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191218165347510.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219055849636.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219060911929.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219061557607.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219062445307.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219062601606.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219064632153.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219064835076.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219065142963.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219065738632.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219093650547.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219103542657.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219103848810.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219104847799.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219105805066.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219111123889.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219111544624.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219114053046.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219124424694.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191219130349361.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191220062954443.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191220063113052.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191220064009310.jpg">
<meta property="og:updated_time" content="2019-12-20T05:09:37.651Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【二】剑指Java面试Offer直通车-Java底层知识：GC相关">
<meta name="twitter:description" content="本文学习《剑指Java面试-Offer直通车》第七章，主要内容为: Java底层知识：GC相关视频课程地址：https://coding.imooc.com/class/303.html项目代码地址：https://gitee.com/aiolos123/java_basic本文部分内容和图片引用自博客：《Java-面试–Java8-JVM内存模型》 https://www.jianshu.com">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20191219091341476.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/12/18/java-interview-offer-2/">





  <title>【二】剑指Java面试Offer直通车-Java底层知识：GC相关 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/12/18/java-interview-offer-2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【二】剑指Java面试Offer直通车-Java底层知识：GC相关</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-12-18T11:59:13+08:00">
                2019-12-18
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Java基础/" itemprop="url" rel="index">
                    <span itemprop="name">Java基础</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文学习《剑指Java面试-Offer直通车》第七章，主要内容为: Java底层知识：GC相关<br>视频课程地址：<a href="https://coding.imooc.com/class/303.html" target="_blank" rel="noopener">https://coding.imooc.com/class/303.html</a><br>项目代码地址：<a href="https://gitee.com/aiolos123/java_basic" target="_blank" rel="noopener">https://gitee.com/aiolos123/java_basic</a><br>本文部分内容和图片引用自博客：《Java-面试–Java8-JVM内存模型》 <a href="https://www.jianshu.com/p/a79b3174c2fb" target="_blank" rel="noopener">https://www.jianshu.com/p/a79b3174c2fb</a><br>其又引用自：《JVM内存模型看这个就够了》 <a href="https://www.nowcoder.com/discuss/151138?type=1" target="_blank" rel="noopener">https://www.nowcoder.com/discuss/151138?type=1</a></p>
<a id="more"></a>

<h2 id="JDK8中的JVM架构图"><a href="#JDK8中的JVM架构图" class="headerlink" title="JDK8中的JVM架构图"></a>JDK8中的JVM架构图</h2><p>首先说一下JDK8中的JVM架构图：<br><img src="/blog/images/20191219091341476.jpg" alt="JDK8中的JVM架构图"><br><img src="/blog/images/20191219092028388.jpg" alt="JDK8中的JVM架构图"></p>
<h2 id="Java垃圾回收机制"><a href="#Java垃圾回收机制" class="headerlink" title="Java垃圾回收机制"></a>Java垃圾回收机制</h2><p>自动化的解决了两个问题：</p>
<ol>
<li>对象内存分配——JVM</li>
<li>回收分配给对象的内存——垃圾回收机制</li>
</ol>
<p>Java垃圾回收机制活动的主要区域：JVM内存模型中的堆</p>
<p>Java垃圾回收机制有：GC、ZGC</p>
<h2 id="垃圾回收之标记算法"><a href="#垃圾回收之标记算法" class="headerlink" title="垃圾回收之标记算法"></a>垃圾回收之标记算法</h2><ol>
<li><p>Java对象被判定为垃圾的标准</p>
<blockquote>
<p>当一个Java对象没有被其他对象所引用时，则这个Java对象就被系统判定为垃圾，其占据的内存将被释放，该对象也将被销毁</p>
</blockquote>
</li>
<li><p>判定对象是否为垃圾的两种算法</p>
<blockquote>
<p>引用计数算法；可达性分析算法；<br>无论是引用计数算法还是可达性分析算法，都是为了<strong>标记</strong>出可被回收的对象（内存块）。</p>
</blockquote>
</li>
</ol>
<table>
<thead>
<tr>
<th>标记算法</th>
<th>引用计数算法</th>
<th>可达性分析算法</th>
</tr>
</thead>
<tbody><tr>
<td>判断标准</td>
<td>通过判断对象的引用数量来决定对象是否可以被回收</td>
<td>通过判断对象的引用链是否可达来决定对象是否可以被回收</td>
</tr>
<tr>
<td>工作原理</td>
<td>在堆中的每个对象实例都会有一个引用计数器。每当一个地方引用这个对象时，计数器值 +1；当引用失效时，计数器值-1。 任何时刻下，引用计数为 0 的对象实例可以被当作垃圾进行回收</td>
<td>垃圾回收器会对内存中的整个对象图进行遍历，从一个节点 GC ROOT 开始，遍历其引用节点，当到达这个节点以后，标记为存活，然后继续遍历这个节点的引用节点，当所有的引用节点遍历完毕之后，剩余的节点则被认为是不可达的节点，即垃圾对象</td>
</tr>
<tr>
<td>优点</td>
<td>垃圾回收执行效率高，垃圾回收对程序正常执行的影响较小</td>
<td>由于引用计数算法存在上述缺陷，所有主流的垃圾回收器一般使用可达性分析算法。</td>
</tr>
<tr>
<td>缺点</td>
<td>无法检测出对象之间相互引用(又称循环引用)的情况，导致内存泄露。比如父对象有一个对子对象的引用，子对象反过来引用该父对象，它们的引用计数永远不可能为 0</td>
<td></td>
</tr>
</tbody></table>
<ol start="3">
<li>可达性分析算法<blockquote>
<p>可达性分析算法是从离散数学中的图论引入的，程序把所有的引用关系看作一张图，从一系列的GC ROOT节点开始，向下搜索，搜索所走过的路径就称为”引用链”。当一个对象与GC ROOT没有任何引用链相连，则说明从GC Root到该对象不可达，则这个对象就可以被回收。</p>
</blockquote>
</li>
</ol>
<p>如下图中的 Object4、Object5 通过GC Root不可达的，所以它们是无用节点。<br><img src="/blog/images/20191218165347510.jpg" alt="可达性分析算法"></p>
<ol start="4">
<li>在可达性分析算法中，可作为 GC Root 的Java对象：<blockquote>
<p>虚拟机栈中引用的对象（即栈帧中的本地变量表中引用的对象，如Object hh = new Object(),则在hh局部变量没有被销毁之前，new Object()对象就是GC Root）<br>方法区中常量引用的对象(如在类中定义一个常量，保存的是某对象a的地址，则被保存的对象a就是GC Root)<br>方法区中类静态属性引用的对象(同上)<br>本地方法栈中Native方法的引用对象<br>活跃线程的引用对象(线程如果是活跃的，则它也是GC Root)</p>
</blockquote>
</li>
</ol>
<h2 id="垃圾回收之回收算法"><a href="#垃圾回收之回收算法" class="headerlink" title="垃圾回收之回收算法"></a>垃圾回收之回收算法</h2><p>垃圾回收算法主要有如下4种：</p>
<table>
<thead>
<tr>
<th>回收算法</th>
<th>标记-清除算法(Mark and Sweep)</th>
<th>复制算法(Copying)</th>
<th>标记-整理算法(Compacting)</th>
<th>分代收集算法(Generational Collector)</th>
</tr>
</thead>
<tbody><tr>
<td>工作过程</td>
<td>该算法将垃圾回收分为两个阶段：1. 标记(从根集合进行扫描，对存活的对象进行标记——使用可达性算法);2. 清除(对堆内存从头到尾进行线性遍历，回收不可达对象内存，同时清除之前可达对象的标识，准备进行下一次扫描)</td>
<td>该算法将可用内存按容量、按一定比例分为对象面和空闲面。并选择其中一块或两块为对象面，其他的为空闲面。对象在对象面上创建，当对象面的内存用完时，将存活的对象从对象面复制到其中一块空闲面，然后将对象面所有对象内存清除</td>
<td>该算法将垃圾回收分为两个阶段：1. 标记(从根集合进行扫描，对存活的对象进行标记————使用可达性算法);2. 整理(移动所有存活的对象，且按照内存地址次序依次排列，然后将末端内存地址以后的内存全部回收)</td>
<td>将堆内存进一步划分为不同区域，按照不同生命周期的对象分配到堆内存不同的区域以采用不同的垃圾回收算法(由于不同对象的生命周期及存活情况是不同的)。</td>
</tr>
<tr>
<td>缺点</td>
<td>由于回收时不移动对象，并且只回收不可达对象，所以容易导致内存碎片化，直到OOM</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>使用场景</td>
<td></td>
<td>该算法适用于对象存活率低的场景，因为需要复制的对象较少。如年轻代；不适用于对象存活率较高的场景，如老年代；现在的商用虚拟机都采用这种算法回收年轻代</td>
<td>适用于老年代对象的回收</td>
<td>主流的垃圾回收算法，是一套垃圾回收算法的组合。目的是提高JVM的回收效率</td>
</tr>
<tr>
<td>图例</td>
<td><img src="/blog/images/20191219055849636.jpg" alt="标记-清除算法"></td>
<td><img src="/blog/images/20191219060911929.jpg" alt="复制算法"></td>
<td><img src="/blog/images/20191219061557607.jpg" alt="标记-整理算法"></td>
<td></td>
</tr>
</tbody></table>
<h3 id="分代收集算法-Generational-Collector"><a href="#分代收集算法-Generational-Collector" class="headerlink" title="分代收集算法(Generational Collector)"></a>分代收集算法(Generational Collector)</h3><ol>
<li><p>JDK7、JDK6的堆内存划分如下图：<br><img src="/blog/images/20191219062445307.jpg" alt="JDK7、JDK6的堆内存划分"></p>
</li>
<li><p>JDK8+的堆内存划分如下图(去掉了永久代)：<br><img src="/blog/images/20191219062601606.jpg" alt="JDK8+的堆内存划分"></p>
</li>
<li><p>在JDK6、7、8+中，年轻代和老年代都被保留下来</p>
<blockquote>
<p>年轻代的对象存活率低，适用于复制算法进行垃圾回收<br>老年代的对象存活率高，适用于标记-清除算法或标记-整理算法进行垃圾回收</p>
</blockquote>
</li>
<li><p>分代收集算法的GC分为两种</p>
<blockquote>
<p>Minor GC: 是发生在年轻代中的垃圾收集工作，采用复制算法。<br>Full GC:  与老年代垃圾回收相关。 由于老年代的垃圾回收，一般都伴随着年轻代的回收</p>
</blockquote>
</li>
</ol>
<p>年轻代是几乎所有Java对象出生的地方，即Java对象申请的内存及存放都是在这块区域。<br>Java中大部分对象都不需要长久的存活，新生代是GC垃圾回收频繁的区域。</p>
<ol start="5">
<li>年轻代分为两个区域——Eden区和两个Survivor区(大小比例为8：1：1)<blockquote>
<p>a. 年轻代的目标：尽可能快速地收集掉那些生命周期短的对象<br>b. Eden区(伊甸园区)：Java对象刚被创建是被发配在这个区域的。<br>c. 两个Survivor区(幸存者区)：每次使用Eden和其中一块Survivor区，当进行垃圾回收时，将Eden和这块Survivor区中存活的对象一次性复制到另一块Survivor区中(通过复制算法)，然后再清理掉Eden区和刚刚使用的Survivor区<br>d. 当Survivor区不够用时，就依赖老年代区域</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191219064632153.jpg" alt="年轻代分为两个区域"></p>
<p>第一次Minor GC的过程如下：<br><img src="/blog/images/20191219064835076.jpg" alt="第一次Minor GC的过程"><br>第二次Minor GC的过程如下：<br><img src="/blog/images/20191219065142963.jpg" alt="第二次Minor GC的过程"><br>第三次Minor GC的过程如下：<br><img src="/blog/images/20191219065738632.jpg" alt="第三次Minor GC的过程"></p>
<p>对象在年轻代中每经过一次Minor GC则年龄加1，当对象达到某个年龄(默认为15岁，也可以通过-XX:MaxTenuringThreshold调整该值)或者Eden区或Survivor区装不下的对象，对象就会进入老年代</p>
<p><strong>总结：年轻代的MinorGC采用复制算法回收垃圾，不用考虑碎片问题，只需移动堆顶指针，按顺序分配，在回收时一次性清空Eden区和某一个Survivor区，简单、粗暴、高效！</strong></p>
<ol start="6">
<li><p>对象如何晋升到老年代</p>
<blockquote>
<p>a. 在经历了一定MinorGC次数依然存活的对象(默认为15次，可通过-XX:MaxTenuringThreshold调整该值)，会进入老年代<br>b. Survivor区或Eden区中存放不下的对象，会直接进入老年代。(对象优先在Eden区分配，如果Eden区空间不够，则触发一次MinorGC,并将其复制到Survivor区，如果Survivor区也存放不下，则进入老年代)<br>c. 新生成的大对象会直接进入老年代。(可通过-XX:+PretenuerSizeThreshold设置该值，超过该值的对象一经创建直接进入老年代)</p>
</blockquote>
</li>
<li><p>常用的GC调优参数<br><img src="/blog/images/20191219093650547.jpg" alt="常用的调优参数"></p>
</li>
<li><p>老年代</p>
<blockquote>
<p>含义： 对象通过上述3种方式可晋升到老年代<br>作用： 存放生命周期较长的对象<br>FullGC：当触发老年代的垃圾回收时，也同时会触发年轻代的回收(Minor GC)，即对整个堆的垃圾回收<br>FullGC 比Minor GC慢(慢10倍以上)，但执行频率低</p>
</blockquote>
</li>
<li><p>触发Full GC的条件：</p>
<blockquote>
<p>老年代空间不足<br>永久代空间不足(针对JDK7及之前版本，JDK8无效)<br>CMS GC时出现promotion failed或concurrent mode failure<br>Minor GC晋升到老年代时的平均大小大于老年代的剩余空间<br>程序中直接调用System.gc()。注意此方法只是提示虚拟机进行垃圾回收，但何时回收仍由JVM决定<br>使用RMI来进行RPC或管理的JDK应用，默认每1小时执行1次Full GC</p>
</blockquote>
</li>
<li><p>JDK8使用元空间替代永久代的原因</p>
<blockquote>
<p>降低Full GC的频率；减少GC负担，提升垃圾回收效率</p>
</blockquote>
</li>
</ol>
<h2 id="常见的垃圾收集器"><a href="#常见的垃圾收集器" class="headerlink" title="常见的垃圾收集器"></a>常见的垃圾收集器</h2><ol>
<li><p>Stop-the-World</p>
<blockquote>
<p>含义：JVM由于要执行GC而停止了应用程序的执行<br>任何一种GC算法中都会发生Stop-the-World<br>当Stop-the-World发生时，除了GC的线程执行外，其他线程都处于等待状态直到GC任务完成<br>多数GC优化实际上就是指通过减少Stop-the-World发生的次数来提高程序性能</p>
</blockquote>
</li>
<li><p>Safepoint</p>
<blockquote>
<p>含义：类似于清理垃圾前通知所有人不准再扔垃圾了<br>在可达性分析过程中，需要在一个快照点进行分析，在这个快照点所有线程都被冻结，这个快照点下所有对象引用关系不会发生变化，这个点就是Safepoint。<br>Safepoint不是随意就出现的，因为不能让程序随意停止。产生Safepoint的地方：方法调用；循环跳转；异常跳转等。<br>一旦GC发生，就会让所有的线程跑到最新的Safepoint再停顿下来,而不在Safepoint的线程则恢复其执行，等到达Safepoint<br>Safepoint数量不能太多(增加程序运行负荷)，也不能太少(GC会等待太长时间)，数量得适中</p>
</blockquote>
</li>
<li><p>JVM的两种运行模式</p>
</li>
</ol>
<table>
<thead>
<tr>
<th>JVM的两种运行模式</th>
<th>Server</th>
<th>Client</th>
</tr>
</thead>
<tbody><tr>
<td>启动速度</td>
<td>较慢</td>
<td>较快</td>
</tr>
<tr>
<td>启动进入稳定期后长期运行时</td>
<td>程序运行速度较快</td>
<td>程序运行速度较慢</td>
</tr>
<tr>
<td>原因</td>
<td>Server模式启用了重量级JVM，对程序优化更多</td>
<td>Client模式启用了轻量级JVM</td>
</tr>
</tbody></table>
<p>查看当前jvm的启动模式的命令<br><img src="/blog/images/20191219103542657.jpg" alt="查看当前jvm的启动模式的命令"></p>
<ol start="4">
<li>常见的垃圾收集器<br><img src="/blog/images/20191219103848810.jpg" alt="常见的垃圾收集器"></li>
</ol>
<h3 id="垃圾回收之年轻代垃圾收集器"><a href="#垃圾回收之年轻代垃圾收集器" class="headerlink" title="垃圾回收之年轻代垃圾收集器"></a>垃圾回收之年轻代垃圾收集器</h3><blockquote>
<p>系统吞吐量 = 运行用户代码时间 / (运行用户代码时间 + 垃圾收集时间)</p>
</blockquote>
<table>
<thead>
<tr>
<th>年轻代垃圾收集器</th>
<th>Serial收集器</th>
<th>ParNew收集器</th>
<th>Parallel Scavenge收集器</th>
</tr>
</thead>
<tbody><tr>
<td>如何使用</td>
<td>在JVM启动时通过-XX:+UseSerialGC参数来指定使用该收集器</td>
<td>在JVM启动时通过-XX:+UseParNewGC参数来指定使用该收集器</td>
<td>在JVM启动时通过-XX:+UseParallelGC参数来指定使用该收集器</td>
</tr>
<tr>
<td>使用算法</td>
<td>复制算法</td>
<td>复制算法</td>
<td>复制算法</td>
</tr>
<tr>
<td>工作原理</td>
<td>Serial收集器是单线程垃圾收集器——即在进行垃圾收集时，必须暂停所有工作线程(一般收集几十M到200M的年轻代垃圾，耗时几十ms到100ms)</td>
<td>ParNew收集器是多线程收集，其余的行为、特点和Serial收集器一样</td>
<td>多线程收集</td>
</tr>
<tr>
<td>使用场景</td>
<td>是JVM运行在Client模式下默认的年轻代收集器</td>
<td>Server模式下首选的年轻代收集器</td>
<td>是JVM运行在Server模式下默认的年轻代收集器</td>
</tr>
<tr>
<td>特点</td>
<td>简单高效</td>
<td>单核执行效率不如Serial，多核下执行效率才有优势(默认开启的收集线程数与CPU数相同)</td>
<td>比起前两个收集器关注用户线程停顿时间，该收集器更关注系统的吞吐量。多核下执行效率才有优势</td>
</tr>
<tr>
<td>图示</td>
<td><img src="/blog/images/20191219104847799.jpg" alt="Serial收集器"></td>
<td><img src="/blog/images/20191219105805066.jpg" alt="ParNew收集器"></td>
<td><img src="/blog/images/20191219111123889.jpg" alt="Parallel Scavenge收集器"></td>
</tr>
</tbody></table>
<p>关注用户线程停顿时间： 适合与用户交互的程序，提升用户体验<br>关注系统的吞吐量：高效率的利用CPU的时间，尽快完成运算任务，适用于后台运算而没有太多交互任务的场景</p>
<h3 id="垃圾回收之老年代垃圾收集器"><a href="#垃圾回收之老年代垃圾收集器" class="headerlink" title="垃圾回收之老年代垃圾收集器"></a>垃圾回收之老年代垃圾收集器</h3><table>
<thead>
<tr>
<th>老年代垃圾收集器</th>
<th>Serial Old收集器</th>
<th>Parallel Old收集器</th>
<th>CMS收集器</th>
</tr>
</thead>
<tbody><tr>
<td>如何使用</td>
<td>通过-XX:+UseSerialOldGC参数来指定</td>
<td>通过-XX:+UseParallelOldGC参数来指定</td>
<td>通过-XX:+UseConcMarkSweepGC参数来指定</td>
</tr>
<tr>
<td>使用算法</td>
<td>标记-整理算法</td>
<td>标记-整理算法</td>
<td>标记-清除算法</td>
</tr>
<tr>
<td>工作原理</td>
<td>单线程收集——即进行垃圾收集时，必须暂停所有工作线程</td>
<td>多线程</td>
<td>见下面的6步</td>
</tr>
<tr>
<td>使用场景</td>
<td>是JVM运行在Client模式下默认的老年代收集器</td>
<td>JDK6之后提供该收集器，适用于注重吞吐量及CPU资源敏感的场合可以优先考虑Parallel Scavenge+ Parallel Old的组合</td>
<td>适用于对程序停顿敏感，并且在程序运行时可以提供更大的内存和更多的CPU资源。如果在JVM中有相对较多，存活时间较长的对象，也更适合使用CMS</td>
</tr>
<tr>
<td>特点</td>
<td>简单高效</td>
<td>吞吐量优先</td>
<td>占据JVM老年代收集器的50%。因为其垃圾回收线程几乎能与用户线程做到同时工作，几乎(意为还是无法做到完全)不需要Stop-the-World,但是尽可能缩短了停顿时间。存在内存碎片化的问题</td>
</tr>
<tr>
<td>图示</td>
<td><img src="/blog/images/20191219111544624.jpg" alt="SerialOld收集器"></td>
<td><img src="/blog/images/20191219114053046.jpg" alt="Parallel Old收集器"></td>
<td><img src="/blog/images/20191219124424694.jpg" alt="CMS收集器"></td>
</tr>
</tbody></table>
<ol>
<li>CMS收集器的垃圾回收过程分为如下6步：<blockquote>
<ol>
<li>初始化标记： 虚拟机要停顿正在执行的任务，即执行stop-the-world。从GC Root扫描到所有与其关联的对象并做标记。这个过程很快就可完成</li>
<li>并发标记：并发追溯标记，程序线程与并发标记线程并发执行，用户感受不到程序停顿</li>
<li>并发预清理：查找在执行并发标记阶段从年轻代晋升到老年代的对象。通过重新扫描减少下一阶段(重新标记)的工作</li>
<li>重新标记：暂停虚拟机(即执行stop-the-world)，垃圾收集线程会扫描CMS堆中的剩余对象，从GC Root开始扫描，这个过程比较耗时。</li>
<li>并发清理：清理垃圾对象，程序线程与垃圾收集线程并发执行，用户感受不到程序停顿</li>
<li>并发重置：重置CMS收集器的数据结构，等待下一次垃圾回收</li>
</ol>
</blockquote>
</li>
</ol>
<h3 id="G1收集器-Garbage-First"><a href="#G1收集器-Garbage-First" class="headerlink" title="G1收集器(Garbage First)"></a>G1收集器(Garbage First)</h3><ol>
<li>既用于年轻代，也用于老年代的垃圾收集器</li>
<li>通过-XX:+UseG1GC参数指定；复制算法+标记-整理算法</li>
<li>使命: 未来替换CMS收集器</li>
<li>特点：并行和并发(使用多个CPU来缩短stop-the-world的时间，与用户线程并发执行)；分代收集(独立管理整个堆，但采用不同的方式来处理新创建对象和经过了多次Minor GC的对象，以获得更好的收集效果);空间整合(基于标记-整理算法，解决了内存碎片的问题)；可预测的停顿(建立可预测停顿时间的模型)</li>
<li>G1收集器将整个Java堆内存划分为多个大小相等的Region。虽然年轻代和老年代仍然存在，但它们不在物理隔离。不需要在JVM启动时决定哪些Region属于年轻代，哪些属于老年代</li>
<li>G1收集器是并行的stop-the-world收集器。当一个年轻代的GC发生时，整个年轻代都回收；G1的老年代收集器比较特殊，不需要整个老年代都回收，因为总有一部分Region被调用</li>
<li>G1的年轻代Region分为：Eden Region和Survivor Region。当JVM分配Eden Region失败(意味着Eden空间已满)后就会触发年轻代回收</li>
<li>JDK11中新出现的GC: EpsilonGC和ZGC</li>
</ol>
<p><img src="/blog/images/20191219130349361.jpg" alt="G1收集器"></p>
<h2 id="垃圾回收之常见面试题"><a href="#垃圾回收之常见面试题" class="headerlink" title="垃圾回收之常见面试题"></a>垃圾回收之常见面试题</h2><ol>
<li>Object的finalize()方法的作用是否与C++的析构函数作用相同<blockquote>
<p>答案：与C++的析构函数不同，析构函数调用时机是确定的，而finalize的调用时机是不确定的</p>
</blockquote>
</li>
</ol>
<p>当Java的垃圾收集器宣告一个对象死亡时，至少要被标记两次(初始标记、重新标记)：如果对象在经过可达性分析后，发现没有与GC Root相连的引用链，就会被第一次标记，并且判断是否执行finalize()方法。如果对象覆盖了finalize()方法且未被引用过，则这个对象就将被放置在F-Queue队列中。并在稍后由JVM自动创建的一个低优先级的finalize线程去执行触发finalize()方法。由于该线程优先级低，所以触发finalize()方法后不承诺等待其运行结束，即finalize()方法执行随时可能被终止。</p>
<p>finalize()方法的作用是为对象创造最后一次重生的机会。</p>
<p>由于finalize()方法执行的不确定性，无法保证各对象的调用顺序，运行代价高昂(sleep1s)，所以不建议使用该方法。示例代码如下：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">FinalizeDemo</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> FinalizeDemo finalizeDemo;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">finalize</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"In finalize()"</span>);</span><br><span class="line">        finalizeDemo = <span class="keyword">this</span>; <span class="comment">//将自身this复制给类成员变量finalizeDemo，使该对象获得重生</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span>(<span class="params">String[] args</span>)</span> &#123;</span><br><span class="line">        FinalizeDemo f = <span class="keyword">new</span> FinalizeDemo();</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"first print:"</span> + f);</span><br><span class="line">        f = <span class="literal">null</span>;</span><br><span class="line">        System.gc(); <span class="comment">//gc()方法会触发finalize()方法</span></span><br><span class="line">        <span class="keyword">try</span>&#123;<span class="comment">//休息一段时间，确保让上面的垃圾回收线程执行完成</span></span><br><span class="line">            Thread.currentThread().sleep(<span class="number">1000</span>);</span><br><span class="line"></span><br><span class="line">        &#125;<span class="keyword">catch</span> (InterruptedException e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"Second print："</span> + f);</span><br><span class="line">        System.<span class="keyword">out</span>.println(f.finalizeDemo);</span><br><span class="line">        <span class="comment">//如果该值打印为null，则是由于finalize()方法未执行到</span></span><br><span class="line">        <span class="comment">// finalizeDemo = this; 就已经被终止，解决办法是加上面的try-catch，让该线程等待一段时间</span></span><br><span class="line">        <span class="comment">// 确保垃圾回收线程执行完finalize()方法</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li><p>Java中的强引用、软引用、弱引用、虚引用有什么作用</p>
<p>| 强引用(Strong Reference) |  软引用(Soft Reference)  | 弱引用(Weak Reference) | 虚引用(Phantom Reference)</p>
</li>
</ol>
<p>-|-|- |-<br>含义|最普遍的引用| 表示对象处在有用但非必须的状态|非必须的对象，比软引用更弱一些| 不会决定对象的生命周期<br>用法|如String str = new String(“abc”) //通过new出的对象实例，str就是强引用|SoftReference<string> softRef = new SoftReference<string>(str);//softRef就是软引用 | WeakReference<string> weakRef = new WeakReference<string>(str);//weakRef就是弱引用| ReferenceQueue queue = new ReferenceQueue();PhantomReference ref = new PhantomReference(str, queue); //ref就是虚引用<br>特点|当内存不足时，JVM宁可抛出OutOfMemoryError异常终止程序也不会回收具有强引用的对象| 可以用来实现内存敏感的高速缓存。这样就无需担心OOM的问题,因为内存空间不足时，GC会回收软引用；而内存空间一般是充足的，便于对象复用|弱引用对象有更短的生命；被回收的概率也不大，因为GC线程优先级比较低；适用于引用偶尔被使用且不影响垃圾收集的对象| 主要用于跟踪对象被GC回收的活动，起哨兵作用；必须和引用队列ReferenceQueue联合使用<br>回收方式|通过将对象显式设置为null来弱化引用，使其被回收。或者等待其超出对象生命周期后由GC来回收|如果一个对象有软引用，当内存空间充足时，GC就不会回收该对象；只有当内存空间不足时，GC才会回收该引用的对象|无论内存是否紧缺，只要GC扫描一旦发现有被弱引用关联的对象就会回收它|如果一个对象只有虚引用，那么它在任何时候都可能被GC回收</string></string></string></string></p>
<ol>
<li><p>四种引用总结如下图<br><img src="/blog/images/20191220062954443.jpg" alt="G1收集器"></p>
</li>
<li><p>四种引用类关系如下图：<br><img src="/blog/images/20191220063113052.jpg" alt="G1收集器"></p>
</li>
<li><p>引用队列(ReferenceQueue)的作用</p>
<blockquote>
<p>名义上是一个队列，但实际上没有存储结构，存储逻辑依赖于内部节点(即引用本身)之间的关系来表达。它是一个链表结构，该队列只存储head节点，后面的节点由引用通过本身的next节点关联</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191220064009310.jpg" alt="G1收集器"></p>
<p>引用队列的作用：某对象被GC完成之后，用来存储与之关联的软引用、弱引用和虚引用<br>引用队列的意义：可以在外部对ReferenceQueue进行监控，如果有对象即将被回收，则相应的Reference对象将被放入到ReferenceQueue中，就可以使用ReferenceQueue做一些事情。如果没有ReferenceQueue，就只能不断轮询Reference对象，通过get()方法来判断是否为null来看对象是否被回收，而这种方式不适用于虚引用(Phantom Reference)，因为它的get()始终为null。</p>
<ol start="4">
<li><p>当创建了一个Reference对象时，如果指定了ReferenceQueue，则当引用对象指向的对象达到合适的状态时，GC会将引用对象本身添加到ReferenceQueue中，方便处理它</p>
</li>
<li><p>什么是”引用对象指向的对象”</p>
<figure class="highlight processing"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//下述代码中，abcWeakRef就是引用对象；str对象就是abcWeakRef引用对象指向的对象；</span></span><br><span class="line"><span class="comment">//当GC回收str实例时，abcWeakRef将被添加到ReferenceQueue中</span></span><br><span class="line"><span class="keyword">String</span> <span class="built_in">str</span> = <span class="keyword">new</span> <span class="keyword">String</span>(<span class="string">"abc"</span>);</span><br><span class="line">WeakReference&lt;<span class="keyword">String</span>&gt; abcWeakRef = <span class="keyword">new</span> WeakReference&lt;<span class="keyword">String</span>&gt;(<span class="built_in">str</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Java面试/" rel="tag"># Java面试</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/12/13/machine-learning-classical-algorithm-2/" rel="next" title="【二】Python3入门机器学习经典算法与应用——Jupyter Notebook, numpy和matplotlib基础">
                <i class="fa fa-chevron-left"></i> 【二】Python3入门机器学习经典算法与应用——Jupyter Notebook, numpy和matplotlib基础
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/12/20/how-to-compression-ajax-data/" rel="prev" title="解决ajax请求后台大量数据时前端页面加载缓慢的问题">
                解决ajax请求后台大量数据时前端页面加载缓慢的问题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#JDK8中的JVM架构图"><span class="nav-number">1.</span> <span class="nav-text">JDK8中的JVM架构图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java垃圾回收机制"><span class="nav-number">2.</span> <span class="nav-text">Java垃圾回收机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#垃圾回收之标记算法"><span class="nav-number">3.</span> <span class="nav-text">垃圾回收之标记算法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#垃圾回收之回收算法"><span class="nav-number">4.</span> <span class="nav-text">垃圾回收之回收算法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#分代收集算法-Generational-Collector"><span class="nav-number">4.1.</span> <span class="nav-text">分代收集算法(Generational Collector)</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#常见的垃圾收集器"><span class="nav-number">5.</span> <span class="nav-text">常见的垃圾收集器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#垃圾回收之年轻代垃圾收集器"><span class="nav-number">5.1.</span> <span class="nav-text">垃圾回收之年轻代垃圾收集器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#垃圾回收之老年代垃圾收集器"><span class="nav-number">5.2.</span> <span class="nav-text">垃圾回收之老年代垃圾收集器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#G1收集器-Garbage-First"><span class="nav-number">5.3.</span> <span class="nav-text">G1收集器(Garbage First)</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#垃圾回收之常见面试题"><span class="nav-number">6.</span> <span class="nav-text">垃圾回收之常见面试题</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
